let { HttpRequest, globalData, mfutil, UserAccess, addUserStat, URLChangeCommon } = getApp();
const app = getApp();
Page({
  data: {
    a: false,
    id: null,
    winActive: false,    //中奖列表展示状态
    radioActive: false,   //单选框状态
    tilesDetail: {        //详情数据
      points: 20,       //需要积分数值
      tile_info: ''
    },
    userActive: null,   //用户是否可以参与活动
    hyperlinkAcitve: false,   //链接图片状态
    digitalActive: false,   //虚拟兑换弹窗
    digitalImG: '',
    canvasWidth: '',
    canvasHeight: '',
    router: '/pages/equity-detail/equity-detail',
    pagetitle: '权益中心详情页',
    scrolly: true,
    scrollTop: 0,
    loadingActive: false
  },
  onLoad(options) {
    my.hideShareMenu({
      success() {
      },
      fail() {
      },
    });
    console.log(options,"opentions---------------------------------------------");
    let { id, url, activetype, gifttype, listbuttontext, gifturl } = options;
    this.setData({
      id,
      activetype,
      gifttype,
      listbuttontext,
      gifturl
    })
    console.log(options,"qqqqqqqqqqqqqqqqqqqqqqqqqeeeeewwwwwww1222");
    let digitalImG = null;
    if (url) {
      this.setData({
        digitalImG: url
      })
    }
    this.initPage()
    /**
* 用户行为记录埋点
*/
    let routerArr = getCurrentPages();
    let params = app.globalData.params;
    let channel = app.globalData.channel;
    let UserAccessoptions = {
      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
      name: routerArr[routerArr.length - 1].data.pagetitle,
      address: options.id,
    }
    let track = UserAccess(UserAccessoptions)



    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileCover_'+options.id,
      // tileId: options.id
    }
    console.log(options.id, '进入Tile封面');

    let tracks = addUserStat(customAccessoptions)
  },
  /**
   * 初始化数据
   */
  async initPage() {
    let { tilesDetail, userActive, id } = this.data;
    let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/get?url=/v2/cms/api/tile/${id}`;
    let parmasObj = {
      member_id_type: 1,
      member_id: globalData.userInfo.memberId
    }
    this.setData({
      loadingActive: true
    })
    let res = await HttpRequest(path, 'POST', parmasObj, {})
    //积分查询 
    let bodyObj2 = {
      // "param": "13800138000",
      // "type": 0,
      "param": globalData.ouid,
      "type": 3
    }
    let path2 = `/vans-family/api/v2.1/project/vansFamily/clm/forward/sendjson/get?url=/v1/points/api/tmall/account`;
    let res2 = await HttpRequest(path2, 'POST', '', bodyObj2);
    if (res2.data.resultCode == 0) {
      globalData.userInfo.availablePoint = res2.data.data.availablePoint;
      globalData.userInfo.willExpirePoint = res2.data.data.willExpirePoint;
    }
    console.log(res2.data,"=============+++++++++++++++++++==============+");

    if (res.data.code == 0) {
      tilesDetail = res.data.data;
      let { availablePoint } = globalData.userInfo;
      let { points, type } = tilesDetail.tile_info;
      userActive = (availablePoint >= points) || points == 0 ? true : false    //用户可用积分/活动所需积分
      this.setData({
        tilesDetail,
        userActive,
        a: true
        // digitalImG: res.data.data.tile_info.gift_url,
      })
      this.setData({
        loadingActive: false
      })
      this.creatCanvas()
    }
    this.setData({
      loadingActive: false
    })

  },
  //单选协议同意/默认
  radioChange() {
    let { radioActive } = this.data;
    this.setData({
      radioActive: !radioActive
    })
  },
  // 中奖页显示/隐藏
  winChange() {
    let { winActive } = this.data;
    this.setData({
      winActive: !winActive
    })
  },
  //赚更多积分跳转
  getIntegralTo() {
    my.alert({
      content: '您的积分不足，无法参与兑礼！'
    })

  },
  /** 
   * 实物立即兑换跳转
  */
  conversionTo(event) {
    console.log(event)
    let { id } = event.currentTarget.dataset;
    my.navigateTo({
      url: `/pages/conversion-page/conversion-page?id=${id}`
    });
  },
  /**
   * 虚拟兑换
   */
  async digitalReward() {
    let { digitalActive, tilesDetail } = this.data;
    let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/")
    let parmasObj = {
      member_id_type: 1,
      member_id: globalData.userInfo.memberId
    }
    let bodyObj = {
      do_datetime: time,
    }
    this.setData({
      loadingActive: true
    })
    let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${tilesDetail.tile_info.type}/${tilesDetail.tile_info.id}/done`;
    let res = await HttpRequest(path, 'POST', parmasObj, bodyObj);
    console.log(res,"2222222222222222errrrrrrttt");
    this.setData({
      loadingActive: false
    })

    if (res.data.code == 0) {
      this.setData({
        digitalActive: !digitalActive,
        digitalImG: res.data.data.url,
        equityType: res.data.data.type,
        gifttype: res.data.data.type,
        gifturl: res.data.data.url
      })
      console.log(digitalImG,"11111111111111111111111111112233");
      this.creatCanvas()

      // globalData.digitalImG = res.data.data.url;
    } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
      my.alert({
        content: res.data.msg
      })
    } else {
      mfutil.launchErrPage(53001)
    }


    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileDone'+this.data.tilesDetail.tile_info.id+'_虚拟兑换TileDone',
      // tileId: this.data.tilesDetail.tile_info.id,
      // points: this.data.tilesDetail.points
    }
     let tracks = addUserStat(customAccessoptions)
    console.log(id, 'TileDone');

  },
  // /虚拟下载
  downLoad() {
    let { digitalImG } = this.data;
    my.saveImage({
      url: digitalImG,
      showActionSheet: true,
      success: () => {
        my.alert({
          title: '下载成功',
        });
      },
      fail: (error) => {
        my.alert({
          title: '下载失败',
          content: error
        });
      }
    });
    // console.log(digitalImG, '=================');
    // this.creatCanvas()
    // my.showLoading({
    //   content: '下载中···',
    //   delay: 2000,
    // });
    // setTimeout(() => {
    //   this.saveImg()
    // }, 2000);
    // my.hideLoading();
  },
  //pdf链接复制
  copyLink() {
    let { digitalImG } = this.data;
    my.setClipboard({
      text: digitalImG,
      success: (res) => {
        my.showToast({
          type: 'success',
          content: '链接复制成功,请前往浏览器下载',
          duration: 1500,
        });
      }
    });
  },
  //创建canvas
  creatCanvas() {
    let { digitalImG, canvasWidth, canvasHeight, imgExist } = this.data;
    const ctx = my.createCanvasContext('myCanvas');
    my.getImageInfo({
      src: digitalImG,
      success: (res) => {
        this.setData({
          canvasWidth: res.width,
          canvasHeight: res.height
        })
        ctx.drawImage(digitalImG, 0, 0, canvasWidth, canvasHeight);
        ctx.draw();
        ctx.save();
      }
    })
  },
  saveImg() {
    const ctx = my.createCanvasContext('myCanvas');
    ctx.draw(false, ctx.toTempFilePath({
      fileType: 'jpg',
      quality: 1,
      success(res) {
        my.saveImage({
          url: res.apFilePath,
          showActionSheet: true,
          success: (res) => {
            my.showToast({
              type: 'success',
              content: '下载成功',
              duration: 1500,
            });
          },
        });
      }
    }));

  },
  /**
   * 立即参与跳转
   */
  async equityDetail2(event) {
    let { tilesDetail, islucky } = this.data;
    let time = new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " ").replace(/\-/g, "/")
    let parmasObj = {
      member_id_type: 1,
      member_id: globalData.userInfo.memberId,
    }
    let bodyObj = {
      do_datetime: time
    }
    let path = `/vans-family/api/v2.1/project/vansFamily/cms/forward/post?url=/v1/cms/api/tile/${tilesDetail.tile_info.type}/${tilesDetail.tile_info.id}/done`;
    this.setData({
      loadingActive: true
    })
    let res = await HttpRequest(path, 'POST', parmasObj, bodyObj);
    this.setData({
      loadingActive: false
    })
    if (res.data.code == 0) {
      this.initPage()
      my.redirectTo({
        url: `/pages/equity-detail2/equity-detail2?id=${tilesDetail.tile_info.id}&method=equity&islucky=false`
      });
      /**
      * 用户行为记录埋点
      */
      let routerArr = getCurrentPages();
      let options = {
        grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
        name: routerArr[routerArr.length - 1].data.pagetitle,
        address: this.data.detailData.tile_info.id
      }
      let track = UserAccess(options)



      // 自定义埋点
      let customAccessoptions = {
        customType: 'TileDone_'+this.data.tilesDetail.tile_info.id+'_立即参与跳转TileDone',
        // tileId: this.data.tilesDetail.tile_info.id,
        // points: this.data.tilesDetail.points
      }
       let tracks = addUserStat(customAccessoptions)
      console.log(id, 'TileDone');
    } else if (res.data.code == 53012 || res.data.code == 53014 || res.data.code == 53001) {
      my.alert({
        content: res.data.msg
      })
    } else {
      mfutil.launchErrPage(53001)
    }
  },
  /**
   * 链接文字点击
   */
  hyperlinkChange() {
    let { hyperlinkAcitve } = this.data;
    this.setData({
      hyperlinkAcitve: !hyperlinkAcitve
    })
  },
  // getIntegralTo() {
  //   my.switchTab({
  //     url: '/pages/getIntegral-page/getIntegral-page'
  //   });
  // },
  equityTo() {
    my.switchTab({
      url: '/pages/equity-page/equity-page',
      success() {
        // let a = getCurrentPages();
        // a[a.length - 2].initPage()
      }
    });
  },
  shareFn() {
    my.showSharePanel();
  },
  // 结束页路由跳转
  urlChange(event) {
    let { item } = event.currentTarget.dataset;
    URLChangeCommon(item)
    /**
* 用户行为记录埋点
*/
    let routerArr = getCurrentPages();
    let params = app.globalData.params;
    let channel = app.globalData.channel;
    let UserAccessoptions = {
      grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
      name: routerArr[routerArr.length - 1].data.pagetitle,
      address: this.data.detailData.tile_info.id,
      String4: item.cta_button_name

    }
    let track = UserAccess(UserAccessoptions)

    // 自定义埋点
    let customAccessoptions = {
      customType: 'TileCTA_'+this.data.detailData.tile_info.id+'_'+item.cta_button_name
    }

    let tracks = addUserStat(customAccessoptions)
  },
  onScroll(event) {
    this.setData({
      scrollTop: event.detail.scrollTop,
      ScrollToUpper: scrollTop == 0 ? true : false
    })
    if (scrollTop == 0) {
      this.setData({
        ScrollToUpper: true
      })
    }
  },
  onTouchStart(event) {
    this.setData({
      starty: event.changedTouches[0].pageY,
    })
  },
  onTouchMove(event) {
    //当前pagey
    this.setData({
      movey: event.changedTouches[0].pageY
    })
    let { scrollTop } = this.data;
    let { ScrollToUpper, ScrollToLower, movey, starty } = this.data;
    if (ScrollToUpper && (starty > movey)) {
      this.setData({
        scrolly: true,
        ScrollToUpper: false,
        ScrollToLower: false
      })
    } else
      if (ScrollToUpper && (starty < movey)) {
        this.setData({
          scrolly: false,
        })
      }
    if (ScrollToLower && (starty < movey)) {
      this.setData({
        scrolly: true,
        ScrollToUpper: false,
        ScrollToLower: false
      })
    } else
      if (ScrollToLower && (starty > movey)) {
        this.setData({
          scrolly: false,
        })
      }
  },
  onScrollToUpper(event) {
    this.setData({
      scrolly: false,
      ScrollToUpper: true,
      ScrollToLower: false
    })
  },
  onScrollToLower() {
    this.setData({
      scrolly: false,
      ScrollToLower: true,
      ScrollToUpper: false
    })
  }
});
